package com.heima.article.service.Imp;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;

@Service
@Slf4j
public class GeneratePageServiceImp implements GeneratePageService {
    @Autowired
    Configuration configuration;
    @Autowired
    @Qualifier("minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Value("${file.minio.prefix}")
    private String prefix;
    @Value("${file.minio.readPath}")
    private String readPath;

    @Override
    public void generateArticlePage(String content, ApArticle apArticle)   {
        try {
            //1.获取Template模板对象
            Template template = configuration.getTemplate("article.ftl");
            //2.准备替换模板的数据（作者的apuser-id ,文章信息 文章详情）
            HashMap<String, Object> map = new HashMap<>();
            //3.基于数据替换模板 得到静态页面 输出内容
            //将json格式转化为集合·
            map.put("content", JSONArray.parseArray(content));
            map.put("article",apArticle);
            //根据作者的id获得作者apUser的id
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            map.put("authorApUserId",apAuthor.getUserId());
            //创建字符输出流
            StringWriter writer = new StringWriter();
            template.process(map,writer);
            //生成需要的输入流writer.toString().getBytes() 生成内存的字符输入流
            String htmlContent = writer.toString();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(htmlContent.getBytes());
            //4.将得到的静态页面上传到 minio中
            String store = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            //5.将上传成功的路径保存到apArticle表中的static_url字段
            String staticUrl = readPath + store;
            log.info("上传minio路径为" + staticUrl);
            apArticle.setStaticUrl(staticUrl);
            apArticleMapper.updateById(apArticle);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            log.error("上传页面异常");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"上传静态页面失败原因" + e.getCause());
        }
    }
}
